package com.zxinlee.order.service.impl;

import com.zxinlee.order.entity.AccountMassage;
import com.zxinlee.order.entity.Order;
import com.zxinlee.order.entity.TxInfo;
import com.zxinlee.order.feign.AccountClient;
import com.zxinlee.order.feign.EasyIdClient;
import com.zxinlee.order.feign.StorageClient;
import com.zxinlee.order.mapper.OrderMapper;
import com.zxinlee.order.mapper.TxMapper;
import com.zxinlee.order.service.OrderService;
import com.zxinlee.order.utli.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Random;
import java.util.UUID;

@Slf4j
@Service
@RocketMQTransactionListener//实现监听器接口
public class OrderServiceImpl implements OrderService, RocketMQLocalTransactionListener {

    @Autowired
    private EasyIdClient easyIdClient;

    @Autowired
    private AccountClient accountClient;

    @Autowired
    private StorageClient storageClient;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Autowired
    private TxMapper txMapper;

    /**
     * 先写核心代码,需要什么数据,再补充代码
     *
     * @param order
     */
    // 发送事务消息
    @Override
    public void create(Order order) {

        String xid = UUID.randomUUID().toString().replace("-", "");

        AccountMassage accountMassage = new AccountMassage(order.getUserId(), order.getMoney(), xid);
        String json = JsonUtil.to(accountMassage);
        //封装成Spring通用 Massage对象
        Message<String> message = MessageBuilder.withPayload(json).build();

        rocketMQTemplate.sendMessageInTransaction(
                "orderTopic",    //  "orderTopic:Tag01"
                message,                    //消息数据
                order                       //业务数据
        );
    }

    @Override
    @Transactional
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) {

        //定义两个状态变量
        RocketMQLocalTransactionState state; //用来返回
        int status; //用来储存到数据库

        try {
            //执行业务
            Order order = (Order) o;
            doCreate(order);
            state = RocketMQLocalTransactionState.COMMIT;
            status = 0; //成功
        } catch (Exception e) {
            log.info("存储订单失败", e);
            state = RocketMQLocalTransactionState.ROLLBACK;
            status = 1;
        }

        // 从 message 中取出 xid
        String json = new String((byte[]) message.getPayload());
        String xid = JsonUtil.getString(json, "xid");
        // 存储本地事务的执行状态
        TxInfo txInfo = new TxInfo(xid, System.currentTimeMillis(), status);
        txMapper.insert(txInfo);
        return state;
    }

    // 处理事务回查
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {

        String json = new String((byte[]) message.getPayload());
        String xid = JsonUtil.getString(json, "xid");
        // 查询事务状态
        TxInfo txInfo = txMapper.selectById(xid);

        if (txInfo == null) return RocketMQLocalTransactionState.UNKNOWN;

        switch (txInfo.getStatus()) {
            case 0:
                return RocketMQLocalTransactionState.COMMIT;
            case 1:
                return RocketMQLocalTransactionState.ROLLBACK;
            //应该不会执行 default ,状态只有 0,1 ,没有其他状态
            default:
                return RocketMQLocalTransactionState.UNKNOWN;
        }
    }

    public void doCreate(Order order) {

        // TODO : 从全局唯一id发号器获得id，这里暂时随机产生一个 orderId
        //Long orderId = Long.valueOf(new Random().nextInt(Integer.MAX_VALUE));
        Long orderId = Long.valueOf(easyIdClient.nextId("order_business"));
        order.setId(orderId);

        orderMapper.create(order);


        // 通过 RockerMQ 异步调用,不是 Feign 方式的远程调用
        //// TODO: 调用storage，修改库存
        //storageClient.decrease(order.getProductId(), order.getCount());
        //
        //// TODO: 调用account，修改账户余额
        //accountClient.decrease(order.getUserId(), order.getMoney());

    }
}
